package com.suxin.thread.manager.pool;

import java.util.concurrent.Executor;

/**
 * @author Tang
 * @classname AbstractSyncRunnable
 * @description [ 抽象的异步任务 ]
 * @date 2022/10/14 17:37
 */
public abstract class AbstractSyncRunnable implements Runnable{

    public Executor executor;

    /**
     * 是否取消执行
     */
    private boolean isCanceled = false;

    public AbstractSyncRunnable(Executor executor) {
        this.executor = executor;
    }

    /**
     * 加入线程池
     */
    public void execute() {
        executor.execute(this);
    }

    public boolean isCanceled() {
        return isCanceled;
    }

    @Override
    public void run() {
        if (isCanceled()) {
            return;
        }
        runTask();
        // 继续执行
        if (isNeedExecute()) {
            execute();
        }
    }

    /**
     * 实际执行的任务方法
     */
    protected abstract void runTask();

    /**
     * 是否需要循环执行
     */
    protected abstract boolean isNeedExecute();
}
